#include "drv_spi_init.h"

void DPM_SpiInit(void)
{
    /* spi clock enable */
    RCC_APB2_Peripheral_Clock_Enable(SPI_W25_PERIPH);
    /* GPIO Periph clock enable */
    RCC_AHB_Peripheral_Clock_Enable(SPI_W25_PERIPH_GPIO);

    GPIO_InitType GPIO_InitStructure;
    GPIO_Structure_Initialize(&GPIO_InitStructure);
    /* Configure slave pins:  SCK, MISO and MOSI */
    /* Confugure SPI pins as Input Floating */
    GPIO_InitStructure.Pin        = SPI_W25_CLK_PIN | SPI_W25_MISO_PIN | SPI_W25_MOSI_PIN | SPI_W25_NSS_PIN ;
    GPIO_InitStructure.GPIO_Mode  = GPIO_MODE_AF_PP;
    GPIO_InitStructure.GPIO_Slew_Rate = GPIO_SLEW_RATE_FAST;
    GPIO_InitStructure.GPIO_Alternate = SPI_W25_GPIO_ALTERNATE;
    GPIO_Peripheral_Initialize(SPI_W25_GPIO, &GPIO_InitStructure);

    // Configure cs pin
    /* Assign default value to GPIO_InitStructure structure */
    GPIO_Structure_Initialize(&GPIO_InitStructure);
    /* Select the GPIO pin to control */
    GPIO_InitStructure.Pin          = SPI_W25_NSS_PIN;
    /* Set pin mode to general push-pull output */
    GPIO_InitStructure.GPIO_Mode    = GPIO_MODE_OUT_PP;
    GPIO_InitStructure.GPIO_Slew_Rate = GPIO_SLEW_RATE_FAST;
    /* Initialize GPIO */
    GPIO_Peripheral_Initialize(SPI_W25_GPIO, &GPIO_InitStructure);
    GPIO_Pins_Set(SPI_W25_GPIO, SPI_W25_NSS_PIN);


    SPI_InitType SPI_InitStructure;
    SPI_Initializes_Structure(&SPI_InitStructure);
    SPI_InitStructure.DataDirection = SPI_DIR_DOUBLELINE_FULLDUPLEX;
    SPI_InitStructure.SpiMode       = SPI_MODE_MASTER;
    SPI_InitStructure.DataLen       = SPI_DATA_SIZE_8BITS;
    SPI_InitStructure.CLKPOL        = SPI_CLKPOL_HIGH;
    SPI_InitStructure.CLKPHA        = SPI_CLKPHA_SECOND_EDGE;
    SPI_InitStructure.NSS           = SPI_NSS_SOFT;
    /* It is recommended that the SPI master mode of the C version chips should not exceed 18MHz */
    SPI_InitStructure.BaudRatePres  = SPI_BR_PRESCALER_2;
    SPI_InitStructure.FirstBit      = SPI_FB_MSB;
    SPI_Initializes(SPI_W25, &SPI_InitStructure);

    // SPI_SS_Output_Disable(SPI_W25);
    SPI_SS_Output_Enable(SPI_W25);    

    SPI_ON(SPI_W25);
}

void DPM_SpiW25Cs_0(void)
{
    GPIO_Pins_Reset(SPI_W25_GPIO, SPI_W25_NSS_PIN);
    // SPI_Set_Nss_Level(SPI_W25, SPI_NSS_LOW);
}

void DPM_SpiW25Cs_1(void)
{
    GPIO_Pins_Set(SPI_W25_GPIO, SPI_W25_NSS_PIN);
    // SPI_Set_Nss_Level(SPI_W25, SPI_NSS_HIGH);
}

void DPM_SpiW25Transimit(uint8_t byte)
{
    SPI_I2S_Data_Transmit(SPI_W25, byte);
}


uint16_t DPM_SpiW25Read(void)
{
    return SPI_I2S_Data_Get(SPI_W25);
}
